<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep, isEmpty } from '@vben/utils';

import { Button, Input, Popconfirm, Space, Table } from 'ant-design-vue';

import Icon from '#/components/Icons';
import { useThemeStore } from '#/store';

// 定义具体类型
interface DataItem {
  key: string;
  [key: string]: any;
}

const columns = ref<
  Array<{
    dataIndex: string;
    ellipsis?: boolean;
    title: string;
    width?: number;
  }>
>([]);
const itemKeys = ref<string[]>([]);
const dataSource = ref<DataItem[]>([]);
const count = computed(() => dataSource.value.length + 1);
function areAllValuesEmpty(obj: any): boolean {
  return Object.values(obj).every((value) => {
    return (
      isEmpty(value) || (typeof value === 'object' && areAllValuesEmpty(value))
    );
  });
}
const [Modal, ModalApi] = useVbenModal({
  footer: false,
  onBeforeClose() {
    ModalApi.setData({
      count: count.value,
      dataSource: dataSource.value,
    });
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      const modalData: any = await ModalApi.getData();
      itemKeys.value = Object.keys(modalData.item);
      columns.value = itemKeys.value.map((key) => ({
        title: modalData.item[key].title,
        dataIndex: key,
        ellipsis: true,
      }));

      // Add "操作" column
      columns.value.push({
        title: '操作',
        dataIndex: 'operation',
        width: 220,
      });

      // Map data with index as key
      dataSource.value = modalData.value.map((item: any, index: number) => ({
        ...item,
        key: `${index}`,
      }));
    }
  },
});

const editableData: UnwrapRef<Record<string, any>> = reactive({});

// 编辑数据
const edit = (key: string) => {
  const item = dataSource.value.find((item) => item.key === key);
  if (item) {
    editableData[key] = cloneDeep(item);
    // 为编辑行的第一个输入框动态添加 id
    editableData[key].id = `input-${key}`;
  }
};

// 保存编辑数据
const save = (key: any) => {
  const item = dataSource.value.find((item) => item.key === key);
  if (item) {
    Object.assign(item, editableData[key]);
    // 复制一个值，在添加成功后，替换掉带isadd的值
    const newEditableData = cloneDeep(editableData[key]);
    // 去掉key提交数据不需要key
    delete editableData[key].key;
    if (editableData[key]?.isadd) {
      // 删除对象中的isadd
      delete editableData[key].isadd;
      delete newEditableData.isadd;
      // 判断是否所有值都为空，如果为空直接删除本行
      if (areAllValuesEmpty(editableData[key])) {
        dataSource.value = dataSource.value.filter((item) => item.key !== key);
      } else {
        useThemeStore().onPostThemesFileBlockWidgetArray(editableData[key], '');
      }
      const index = dataSource.value.findIndex((item) => item.key === key);
      if (index !== -1) {
        dataSource.value[index] = newEditableData;
      }
    } else {
      useThemeStore().onPostThemesFileBlockWidgetArray(editableData[key], key);
    }

    delete editableData[key];
  }
};

// 删除数据
const onDelete = (key: string) => {
  useThemeStore().onDeleteThemesFileBlockWidgetArray(key);
  dataSource.value = dataSource.value.filter((item) => item.key !== key);
};

// 取消编辑
const cancel = (key: string) => {
  if (editableData[key]?.isadd) {
    dataSource.value = dataSource.value.filter((item) => item.key !== key);
  }
  delete editableData[key];
};

// 添加新数据项并直接编辑
const handleAdd = () => {
  if (dataSource.value.some((item) => item.isadd)) return; // 判断是否已有未保存的新增数据

  const newData: DataItem = { key: `${count.value}`, isadd: true };
  itemKeys.value.forEach((key) => {
    newData[key] = '';
  });

  // 将新数据项添加到数据源中
  dataSource.value.push(newData);

  // 激活编辑状态
  editableData[newData.key] = cloneDeep(newData);

  // 为新增数据项的第一个输入框动态添加 id
  editableData[newData.key].id = `input-${newData.key}`;

  // 等待 DOM 更新后聚焦第一个输入框
  nextTick(() => {
    // eslint-disable-next-line unicorn/prefer-query-selector
    const firstInput = document.getElementById(`input-${newData.key}`); // 使用动态 id 获取第一个输入框
    if (firstInput) {
      firstInput.focus(); // 聚焦第一个输入框
    }
  });
};
</script>

<template>
  <Modal class="w-4/5">
    <Button class="mb-4" type="primary" @click="handleAdd"> 添加 </Button>
    <Table
      :columns="columns"
      :data-source="dataSource"
      :pagination="false"
      bordered
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <div v-if="editableData[record.key]">
              <Space>
                <Button type="primary" @click="save(record.key)">
                  <template #icon>
                    <span class="anticon">
                      <Icon icon="ri:save-line" />
                    </span>
                  </template>
                  保存
                </Button>
                <Popconfirm title="确定要取消吗?" @confirm="cancel(record.key)">
                  <Button ghost type="primary">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:close-fill" />
                      </span>
                    </template>
                    取消
                  </Button>
                </Popconfirm>
              </Space>
            </div>
            <div v-else>
              <Space>
                <Button type="primary" @click="edit(record.key)">
                  <template #icon>
                    <span class="anticon">
                      <Icon icon="ri:file-edit-line" />
                    </span>
                  </template>
                  编辑
                </Button>
                <Popconfirm
                  v-if="dataSource.length > 0"
                  title="确定要删除吗?"
                  @confirm="onDelete(record.key)"
                >
                  <Button danger type="primary">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:delete-bin-line" />
                      </span>
                    </template>
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            </div>
          </div>
        </template>
        <template v-else>
          <div>
            <Input
              v-if="editableData[record.key]"
              :id="editableData[record.key]?.id"
              v-model:value="
                editableData[record.key][column.dataIndex as number]
              "
              style="margin: -5px 0"
            />
            <template v-else> {{ text }} </template>
          </div>
        </template>
      </template>
    </Table>
  </Modal>
</template>
